#include "ZPort.h"

int CAS(int *dest, int old_value, int new_value) {
    int prev = 0;
#ifdef WIN32
    __asm {
        mov eax, old_value
        mov edx, new_value
        mov ecx, dest
        lock cmpxchg [ecx], edx
        mov prev, eax
    }
#else
    asm volatile ("lock; cmpxchgl %1, %2"
                  : "=a" (prev)
                  : "r" (new_value), "m" (*(dest)), "0"(old_value)
                  : "memory", "cc");
#endif
    return prev == old_value;
}

void Inc_m(int *dest, int n) {
    int old;
    do {
        old = *dest;
    } while(!CAS(dest, old, old + n));
}

void Dec_m(int *dest, int n) {
    int old;
    do {
        old = *dest;
    } while(!CAS(dest, old, old - n));
}
